const bodyParser = require("body-parser");
const express = require("express");
const jwt = require('jsonwebtoken')
const app = express()

const main = require('./router/main')


require('./database/init')

// 设置跨域和相应数据格式  
// 解决跨域
app.all('*', function (req, res, next)
{
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken, Authorization, Content-Type, Content-Length, Accept, X-Requested-With');
    res.setHeader('Content-Type', 'application/json;charset=utf-8');
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    res.header('X-Powered-By', ' 3.2.1');

    if (req.method === 'OPTIONS') {
        res.sendStatus(204);
    } else {
        next();
    }
});


app.get('/', (req, res) =>
{
    res.status(404).send({
        data: null,
        meta: {
            msg: "Not Found",
            status: 404
        }
    })
})


app.use('/api', (req, res, next) =>
{
    if (req.url == '/login' || req.url == '/register') {
        next()
        return
    }
    // 接收客户端传递过来的 token
    const token = String(req.headers.authorization)
    console.log(token, 'token');
    const tokenWithoutBearer = token.replace('Bearer ', ''); // 去掉 Bearer 前缀
    const account = jwt.decode(tokenWithoutBearer, 'chengfeng');
    // 解析 token 如果解析失败 返回的是 null
    console.log(account, 'account');
    // 判断客户端是否传递了 token
    if (token == 'undefined' || account == null) {
        res.status(400).send({
            data: null,
            meta: {
                msg: "token无效",
                status: 400
            }
        })
        return
    }
    req.account = account;
    // 直接放行
    next()
})

//全局解析
app.use(bodyParser());
// app.use(bodyParser.urlencoded({ extended: false }))
app.use('/api', main)
// app.listen(8888)
const port = 8888;
app.listen(port, '0.0.0.0', () =>
{
    console.log(`Server is running on http://0.0.0.0:${port}`);
});